package com.achievement.controller;

import com.achievement.domain.dto.PatentDTO;
import com.achievement.domain.entity.PatentEntity;
import com.achievement.domain.param.PatentParam;
import com.achievement.domain.vo.PatentVO;
import com.achievement.service.IPatentService;
import com.alibaba.fastjson2.JSONObject;
import com.common.annotation.Log;
import com.common.core.controller.BaseController;
import com.common.core.domain.AjaxResult;
import com.common.core.page.TableDataInfo;
import com.common.enums.BusinessType;
import com.common.utils.poi.ExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Field;
import java.util.*;

@RestController
@RequestMapping("/achievement/patent")
@Api(tags = "成果管理模块---专利管理")
public class PatentController extends BaseController
{
    @Autowired
    private IPatentService patentService;


    @PreAuthorize("@ss.hasPermi('achievement:patent:list')")
    @GetMapping("/page")
    @ApiOperation(value = "分页获取专利列表", notes = "分页获取专利列表")
    public TableDataInfo list(PatentParam param)
    {
        startPage();
        List<PatentVO> list = patentService.selectByPage(param);
        return getDataTable(list);
    }

    /**
     * 左上方统计 全部 未启动 申请中 已停止
     * @param param 检索参数
     * @return AjaxResult
     */
    @PreAuthorize("@ss.hasPermi('achievement:patent:list')")
    @GetMapping(value = "/list-statistics")
    public AjaxResult listStatistics(PatentParam param)
    {
        List<HashMap<String, Integer>> list =patentService.listStatistics(param);

        return success(list);
    }

    /**
     * 专利成果导出
     */
    @PreAuthorize("@ss.hasPermi('achievement:patent:export')")
    @Log(title = "专利成果导出", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ApiOperation(value = "专利成果导出", notes = "专利成果导出")
    public void export(HttpServletResponse response,@RequestBody Map<String,Object> requestMap) {
        PatentParam param = JSONObject.parseObject(JSONObject.toJSONString(requestMap), PatentParam.class);
        List<String> selectedColumns = (List<String>) requestMap.get("selectedColumns");

        List<PatentEntity> list = patentService.getListByConditions(param);
        ExcelUtil<PatentEntity> util = new ExcelUtil<>(PatentEntity.class);
        util.showColumn(selectedColumns.toArray(new String[0]));
        util.exportExcel(response, list, "专利成果导出数据");
    }

    /**
     * 获取专利详细信息
     */
    @PreAuthorize("@ss.hasPermi('achievement:patent:query')")
    @GetMapping(value = "/{id}")
    @ApiOperation(value = "获取专利详情", notes = "获取专利详情")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return success(patentService.getInfoById(id));
    }

    /**
     * 新增专利
     */
    @PreAuthorize("@ss.hasPermi('achievement:patent:add')")
    @Log(title = "新增专利", businessType = BusinessType.INSERT)
    @PostMapping(value = "/add")
    @ApiOperation(value = "添加专利", notes = "添加专利")
    public AjaxResult add(@RequestBody PatentDTO dto) {
        AjaxResult result = patentService.add(dto);
        return result;
    }

    /**
     * 修改专利
     */
    @PreAuthorize("@ss.hasPermi('achievement:patent:edit')")
    @Log(title = "修改专利", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/update")
    @ApiOperation(value = "编辑专利", notes = "编辑专利")
    public AjaxResult edit(@RequestBody PatentDTO dto) {
        return patentService.update(dto);
    }

    /**
     * 删除专利
     */
    @PreAuthorize("@ss.hasPermi('achievement:patent:remove')")
    @Log(title = "删除专利", businessType = BusinessType.DELETE)
	@DeleteMapping("/del")
    @ApiOperation(value = "删除专利", notes = "删除专利")
    public AjaxResult remove(@RequestBody List<String> ids)
    {
        return toAjax(patentService.batchRemove(ids));
    }



    private String[] getHideColumn(List<String> selectedColumn,Class<?> clazz) {
        List<String> columns = new ArrayList<>();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
//            Excel excelAnnotation = field.getAnnotation(Excel.class);
//            if (excelAnnotation != null) {
//                columns.add(excelAnnotation.name()); // 获取注解中的列名
//            } else {
//                columns.add(field.getName()); // 默认使用属性名
//            }
            columns.add(field.getName());
        }
        String[] allColumns = columns.toArray(new String[0]);
        // 将 selectedColumns 转换为 Set，以便更快地检查是否包含某个属性
        Set<String> selectedSet = new HashSet<>(selectedColumn);
        for (String column : selectedColumn) {
            if (!selectedSet.contains(column)) {
                throw new IllegalArgumentException("无效列名: " + column);
            }
        }
        // 使用列表来存储未选择的列
        List<String> remainingColumns = new ArrayList<>();
        // 遍历所有列，并将未选择的列添加到 remainingColumns 列表中
        for (String column : allColumns) {
            if (!selectedSet.contains(column)) {
                remainingColumns.add(column);
            }
        }
        // 将 remainingColumns 转换回数组
        String[] hideColumns = remainingColumns.toArray(new String[0]);
        return hideColumns;
    }
}
